<template>
	<div>
		<div class="post">
			<article class="post-block">
				<h1 class="post-title">{{ blog.title }}</h1>
				<div class="post-info">
					<!-- <div>{{ blog.author }} {{ blog.changeTime | formatDate }}</div> -->
					<div class="post-meta" style="margin-top: 2px;">
						<!-- <i v-if="blog.pageViews > fire" aria-hidden="true" class="fa fa-free-code-camp animated faa-float" style="color: red;font-weight: 800;"></i>
						<i v-else aria-hidden="true" class="fa fa-eye"></i>
						阅读({{ blog.pageViews }})
						<span id="praise_span" class="faa-parent animated-hover" @click="praise">
							<i aria-hidden="true" class="fa fa-thumbs-up faa-slow faa-vertical" style="margin-left: 20px;"></i>
							点赞({{ blog.praise }})
						</span> -->
					</div>
					<div class="blog_copyright" v-if="showCopy">
						本站所有内容受
						<a href="http://www.npc.gov.cn/npc/c30834/202011/272b72cdb759458d94c9b875350b1ab5.shtml" target="_blank">《著作权法》</a>
						保护.本站开放转载权限,但若转载后未在内容末尾附带本站链接,视为未经作者授权,作者保留对其追究法律责任的权利.
						<a class="copyContent" href="#">已知悉,点此复制</a>
					</div>
				</div>
				<div v-highlight class="post-entry" oncopy="return false;" oncut="return false;" v-html="blog.content"></div>
			</article>
		</div>
		<div class="post-nav">
			<div class="prev-wrap col-md-6 col-xs-6">
				<div v-if="blog.lastRoute != null">
					<a :href="'/blog/' + blog.lastRoute" class="prev-post">
						<i class="fa fa-angle-double-left"></i> {{ blog.lastTitle }}
					</a>
				</div>
			</div>
			<div class="next-wrap col-md-6 col-xs-6">
				<div v-if="blog.nextRoute != null">
					<a :href="'/blog/' + blog.nextRoute" class="next-post">
						{{ blog.nextTitle }} <i class="fa fa-angle-double-right"></i>
					</a>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	// 创建showdown实例（实现markdown转html）
	var converter = new showdown.Converter();
	module.exports = {
		name: "blog",
		// 注意：httpVueLoader.js使用props传递参数时，需要参数名称全部小写（大小写混合情况，只能通过this.$attrs获取到属性值，但是不能建立props）
		props: ['route', 'fire'],
		data() {
			return {
				errorMsg: '',
				showCopy: false,
				blog: {
					/*上一篇路由*/
					lastRoute: null,
					/*上一篇路由标题*/
					lastTitle: null,
					/*下一篇路由*/
					nextRoute: null,
					/*下一篇路由标题*/
					nextTitle: null,
					/*路由*/
					route: '',
					/*标题*/
					title: '',
					/*变更时间*/
					changeTime: '',
					/*作者*/
					author: '',
					/*内容*/
					content: '',
					/*点赞量*/
					praise: '',
					/*总浏览量*/
					pageViews: '',
				}
			}
		},
		//在这里调用ajax请求方法
		created() {
			this.loadBlog();
		},
		mounted() {
			$('.post-entry').on('click', 'img', function() {
				var src = $(this)[0].src;
				console.log(src)

			});
		},
		// 定义自定义指令 v-highlight 代码高亮
		directives: {
			highlight: {
				update(el) {
					let blocks = el.querySelectorAll("pre code");
					blocks.forEach((block) => {
						hljs.highlightBlock(block);
					});
				},
			},
		},
		methods: {
			loadBlog() {
				// http://127.0.0.1:8848/bok/index.html?route=blog&title=author_concise.md&path=/blog/author_concise.md
				let this_ = this;
				this_.blog.title = app.getQueryString('title');
				const path = app.getQueryString('path');
				const fileType = path.split(".").pop();
				if (['jpg', 'png', 'gif', 'txt', 'md', 'docx', 'xls', 'xlsx'].includes(fileType)) {
					this.showCopy = true;
					axios.get(path, {
												responseType: 'arraybuffer'
											})
											.then(function(response) {
												if (response.status == 200) {
													const arrayBuffer = response.data;
													let txtContent = new TextDecoder('utf-8').decode(arrayBuffer);
													const contentType = response.headers['content-type'];
													console.log(contentType)
													if (contentType.includes('text/markdown')) {
														// Markdown 文件
														this_.blog.content = converter.makeHtml(txtContent);
													} else if (contentType.includes('image/jpeg') || contentType.includes('image/png') || contentType.includes('image/gif')) {
														// 图片
														const base64 = btoa(new Uint8Array(arrayBuffer).reduce((data, byte) => data + String.fromCharCode(byte), ''));
														const url = `data:${contentType};base64,${base64}`;
														this_.blog.content = `<img src='${url}'>`;
														txtContent = this_.blog.content;
													} else if (contentType.includes('application/msword')) {
														// doc
														this_.blog.content = txtContent;
													} else if (contentType.includes('application/vnd.openxmlformats-officedocument.wordprocessingml.document')) {
														// docx
														window.mammoth.convertToHtml({
																arrayBuffer: arrayBuffer
															}, {})
															.then(result => {
																this_.blog.content = result.value;
																txtContent = this_.blog.content;
															})
															.catch(error => {
																console.error(error);
															});
													} else if (contentType.includes('application/vnd.ms-excel') || contentType.includes('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')) {
														// xls、xlsx
														const workbook = XLSX.read(arrayBuffer, {
															type: 'buffer'
														});
														const sheetName = workbook.SheetNames[0];
														const sheet = workbook.Sheets[sheetName];
														// 将Excel数据转换为HTML
														this_.blog.content = XLSX.utils.sheet_to_html(sheet);
														txtContent = this_.blog.content;
													} else if (contentType.includes('application/vnd.openxmlformats-officedocument.presentationml.presentation')) {
														// pptx
													} else {
														// 其他文件类型
														this_.blog.content = txtContent;
													}
													let content = (txtContent + '').replace(/\\r\\n/g, `
					`);
													content = content + `
					
					本博文转载自：[G-BLOG](` + window.location.href + ')';
					
													new ClipboardJS('.copyContent', {
														text() {
															layer.msg('复制成功!');
															return content;
														}
													});
												} else {
													window.location.href = '?route=404/notFind';
												}
											}).catch(function(error) {
												window.location.href = '?route=404/' + path;
											});
				} else {
					this.blog.content = `<iframe src="${path}" width="100%" height="600px"></iframe>`;
				}
			},
			praise() {
				let this_ = this;
				/* axios.get('/server/praise' + this_.route.substr(5), {
				  params: {}
				}).then(function (response) {
				  if (response.data.code == 200) {
				    this_.blog.praise += 1;
				  } else {
				    layer.msg('请求失败，[' + response.data.code + ']' + response.data.msg, {time: 1500});
				  }
				}).catch(function (error) {
				  console.log(error);
				}); */
			},
		},
		filters: {
			formatDate(value) {
				let date = new Date(value);
				let y = date.getFullYear();
				let MM = date.getMonth() + 1;
				MM = MM < 10 ? ('0' + MM) : MM;
				let d = date.getDate();
				d = d < 10 ? ('0' + d) : d;
				let h = date.getHours();
				h = h < 10 ? ('0' + h) : h;
				let m = date.getMinutes();
				m = m < 10 ? ('0' + m) : m;
				let s = date.getSeconds();
				s = s < 10 ? ('0' + s) : s;
				return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
			},
		}
	}
</script>
<style scoped>
	.blog_copyright {
		font-size: 12px;
		color: red;
		margin: 10px 40px;
	}
</style>
